package shake

import (
	"data/config"
	"data/view"
	"log"
	"public/mycache"
	"public/mysqldb"
	"public/tools"
	"time"
)

var configMp map[string]Range

func init() {
	//先从缓存中获取
	cache := mycache.OnGetCache("wingame_config")
	var tp interface{}
	tp, b := cache.Value("normal")
	if b {
		configMp = tp.(map[string]Range)
	} else {
		var db mysqldb.MySqlDB
		defer db.OnDestoryDB()
		orm := db.OnGetDBOrm(config.GetDbUrl())

		var config []view.Card_config_tbl
		orm.Order("odds asc").Find(&config)
		if len(config) > 0 {
			configMp = make(map[string]Range)
			info := make(map[string]view.Card_config_tbl)
			for k, v := range config {
				var tmp Range
				if k == 0 {
					tmp.Min = 1
					tmp.Max = k + v.Odds
				} else {
					tmp.Min = configMp[config[k-1].Title].Max + 1
					tmp.Max = configMp[config[k-1].Title].Max + v.Odds
				}
				tmp.Odds = v.Odds
				configMp[v.Title] = tmp
				info[v.Card_id] = v
			}
			//保存缓存
			cache.Add("normal", configMp, 24*time.Hour)
			cache.Add("all", info, 24*time.Hour)
		}

	}

}

//获取随机卡券ID
func GetRandomCard() (card view.Card_config_tbl) {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	random := tools.GetGetRandInt(1, 101) //1-100

	odds := GetRange(random) //所在的概率

	log.Println("rrrrrrrrrrrr", random)
	log.Println("wwwwwwwwwwww", odds)
	orm.Raw("select * from card_config_tbl where odds = ? ORDER BY RAND() LIMIT 1 ", odds).Scan(&card) //随机card_id

	return
}

//获取所在范围的odds
func GetRange(random int) (odds int) {
	if len(configMp) > 0 {
		for _, v := range configMp {
			if v.Min <= random && v.Max >= random {
				odds = v.Odds
			}
		}
	}
	return
}

//1 ==>1
//2 3 4 5  ==>4
//6 7 8 9 ==>4
//10 11 12 13 14 15 16 17 ==>8
//18 19 20 21 22 23 24 25 ==>8
//26 ~ 40 ==>15
//41 ~55 ==>15
//56 ~ 70 ==>15
//71 ~ 85 ==>15
//86 ~ 100 ==>15
